import React, { useRef, useState, useEffect } from 'react';
import { Row, Col, Card, Statistic, Table, Modal, Button,message,Progress  } from 'antd';
import { PlusCircleTwoTone, MinusCircleTwoTone } from '@ant-design/icons';
import { getZtbData,getTodayBk,getNewJyr,getStockData,insertBkMonitor,insertBkZtb,insertStockMonitor } from '../../service/apis/quotation';
import './index.css';
import KLines from '@/components/klines';
import ReactECharts from 'echarts-for-react';
import { getAllDpInfo, getDpInfo } from '@/service/apis/monitor';

const MyComponent: React.FC = () => {
  const [dpInfo, setDpInfo] = useState({
    ztNum: 0,
    dtNum: 0,
    szNum: 0,
    xdNum: 0,
    qd: 0,
    jyr: 0,
    fValue:0,
    vValue:0,
    zqxy: 0,
    zrdbZqxy:0,
    highKpzqxy: 0,
    ztZqxy: 0,
    dbZqxy: 0
  });
  const [tableData, setTableData] = useState([]);
  const [table2Data, setTable2Data] = useState([]);
  const [expandedRowKeys, setExpandedRowKeys] = useState([]);
  const [curJyr, setCurJyr] = useState('');
  const [lbData, setLbData] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedStockData, setSelectedStockData] = useState(null);
  const [lineData, setLineData] = useState([]);
    const [columnData, setColumnData] = useState([]);
  
    const getCircleColor = (percent) => {
      const red = Math.min(255, Math.floor((percent / 100) * 255));
      return `rgb(${red}, 0, 0)`;
    };
  
    const getCombinedOption = () => ({
      tooltip: {
        trigger: 'axis',
        formatter: (params) => {
          const date = new Date(params[0].axisValue);
          const year = date.getFullYear();
          const month = (date.getMonth() + 1).toString().padStart(2, '0');
          const day = date.getDate().toString().padStart(2, '0');
          const formattedDate = `${year}/${month}/${day}`;
          const marketStrength = params[0].data;
          const profitEffect = (Number(params[1].data)*1000).toFixed(0);
          return `日期: ${formattedDate}<br/>市场强度: ${marketStrength}<br/>成交量: ${profitEffect} 亿`;
        },
      },
      legend: {
        data: ['市场强度', '赚钱效应'],
      },
      xAxis: {
        type: 'category',
        data: lineData.map(item => item.date),
        axisLabel: {
          formatter: (value) => {
            const date = new Date(value);
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            return `${month}/${day}`;
          },
        },
        axisPointer: {
          type: 'shadow',
        },
      },
      yAxis: {
        type: 'value',
        max: 100,
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
          },
        },
        axisLabel: {
          formatter: '{value}',
        },
        splitArea: {
          show: true,
          areaStyle: {
            color: ['transparent', 'rgba(154, 220, 141, 0.2)', 'transparent'],
          },
        },
      },
      dataZoom: [
        {
          type: 'inside',
          start: 65,
          end: 100,
        },
        {
          start: 65,
          end: 100,
        },
      ],
  
      series: [
        {
          name: '市场强度',
          type: 'line',
          data: lineData.map(item => item.value),
          lineStyle: {
            color: 'red',
          },
          markPoint: {
            data: [
              {
                coord: [dpInfo.jyr, dpInfo.qd],
                value: dpInfo.qd,
                symbol: 'pin',
                symbolSize: 50,
                label: {
                  show: true,
                  formatter: `{c}`,
                  color: 'white',
                },
                itemStyle: {
                  color: 'red',
                },
              },
            ],
          },
        },
        {
          name: '成交量',
          type: 'bar',
          data: columnData.map(item => item.value),
          itemStyle: {
            color: 'green',
          },
          barWidth: '60%',
        },
      ],
    });

  const columns = [
    // {
    //   title: '代码',
    //   dataIndex: 'code',
    //   key: 'code',
    // },
    {
      title: '板块名称',
      align: 'center',
      dataIndex: 'name',
      key: 'name',
      width: 100, // 固定列宽
      render: (text: string, record: any) => (
        <div style={{ textAlign: 'center' }}>
          <div>{text ? text : '-'}</div>
          <div>
            <Button type="link" onClick={() => handleCodeClick(record.code)}>
              {record.code}
            </Button>
          </div>
        </div>
      ),
    },
    {
      title: '强度',
      align: 'center',
      dataIndex: 'qd',
      key: 'qd',
      render: (text: number) => (text !== null && text !== undefined ? text : '-'),
    },
    {
      title: '涨幅',
      align: 'center',
      dataIndex: 'inc',
      key: 'inc',
      render: (text: number) => (
        <span style={{ color: text > 0 ? '#cf1322' : '#3f8600' }}>{text !== null && text !== undefined ?Number(text).toFixed(2)+'%' :'-'}</span>
      ),
    },
    // {
    //   title: '涨速',
    //   dataIndex: 'zs',
    //   key: 'zs',
    //   render: (text: number) => (
    //     <span style={{ color: text > 0 ? '#cf1322' : '#3f8600' }}>{Number(text).toFixed(2)}%</span>
    //   ),
    // },
    {
      title: '净流入',
      align: 'center',
      dataIndex: 'jlr',
      key: 'jlr',
      render: (text: number) => (
        <span style={{ color: text > 0 ? '#cf1322' : '#3f8600' }}>{text !== null && text !== undefined ?(Number(text)/100000000).toFixed(2)+'亿':'-'}</span>
      ),
    },
    // {
    //   title: '成交额',
    //   align: 'center',
    //   dataIndex: 'money',
    //   key: 'money',
    //   render: (text: number) => (
    //     <span>{text !== null && text !== undefined ?(Number(text)/100000000).toFixed(2)+'亿':'-'}</span>
    //   ),
    // },
    // {
    //   title: '涨停家数',
    //   dataIndex: 'ztNum',
    //   key: 'ztNum',
    // },
    // {
    //   title: '跌停家数',
    //   dataIndex: 'dtNum',
    //   key: 'dtNum',
    // },
    {
      title: '操作',
      align: 'center',
      key: 'action',
      render: (text: string, record: any) => (
        <Button type="link" onClick={() => handleBkMonitor(record.code,record.children != null)}>加入监控</Button>
      ),
    },
  ];
  
  const columns2 = [
    {
      title: '股票',
      align: 'center',
      dataIndex: 'stockName',
      key: 'stockName',
      render: (text: string, record: any) => (
        <div style={{ textAlign: 'center' }}>
          <div>{text ? text : '-'}</div>
          <div>
            <Button type="link" onClick={() => handleStockClick(record.stockCode)}>
              {record.stockCode}
            </Button>
          </div>
        </div>
      ),
    },
    {
      title: '涨幅',
      align: 'center',
      dataIndex: 'inc',
      key: 'inc',
      render: (text: number) => (
        <span style={{ color: text > 0 ? '#cf1322' : '#3f8600' }}>
          {text !== null && text !== undefined ? Number(text).toFixed(2)+'%' : '-'}
        </span>
      ),
    },
    {
      title: '地位',
      align: 'center',
      dataIndex: 'sort',
      key: 'sort',
    },
    {
      title: '连扳',
      align: 'center',
      dataIndex: 'lbDesc',
      key: 'lbDesc',
      render: (text) => (
        <span style={{ color: text !== null && text !== undefined ? '#cf1322' : '#3f8600' }}>
          {text}
        </span>
      ),
    },
    {
      title: '涨停原因',
      align: 'center',
      dataIndex: 'remark',
      key: 'remark',
    },
    // {
    //   title: '操作',
    //   align: 'center',
    //   key: 'action',
    //   render: (record:any) => (
    //     <Button type="link" onClick={() => handleStockMonitor(record.stockCode,record.tagCode)}>加入监控</Button>
    //   ),
    // },
  ];
  
  const columns3 = [
    {
      title: '连扳',
      dataIndex: 'lbNum',
      key: 'lbNum',
      align: 'center',
      render: (text, row, index) => {
        const obj = {
          children: `${text}连扳`,
          props: {},
        };
        if (index > 0 && text === lbData[index - 1].lbNum) {
          obj.props.rowSpan = 0;
        } else {
          let rowSpan = 1;
          for (let i = index + 1; i < lbData.length; i++) {
            if (lbData[i].lbNum === text) {
              rowSpan++;
            } else {
              break;
            }
          }
          obj.props.rowSpan = rowSpan;
        }
        return obj;
      },
    },
    {
      title: '股票',
      align: 'center',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: any) => (
        <div style={{ textAlign: 'center' }}>
          <div>{text ? text : '-'}</div>
          <div>
            <Button type="link" onClick={() => handleStockClick(record.code)}>
              {record.code}
            </Button>
          </div>
        </div>
      ),
    },
    {
      title: '涨幅',
      align: 'center',
      dataIndex: 'inc',
      key: 'inc',
      render: (text: number) => (
        <span style={{ color: text > 0 ? '#cf1322' : '#3f8600' }}>
          {text !== null && text !== undefined ? Number(text).toFixed(2)+'%' : '-'}
        </span>
      ),
    },
    {
      title: '成交额',
      align: 'center',
      dataIndex: 'cValue',
      key: 'cValue',
      render: (text: number) => (
        <span>{text !== null && text !== undefined ?(Number(text)/100000000).toFixed(2)+'亿':'-'}</span>
      ),
    },
    {
      title: '封板资金',
      align: 'center',
      dataIndex: 'fbValue',
      key: 'fbValue',
      render: (text: number) => (
        <span>{text !== null && text !== undefined ?(Number(text)/100000000).toFixed(2)+'亿':'-'}</span>
      ),
    },
    {
      title: '封板时间',
      align: 'center',
      dataIndex: 'lastFbTime',
      key: 'lastFbTime',
      render: (text: number) => {
        const formatTime = (time: number) => {
          const str = time.toString().padStart(6, '0');
          return `${str.slice(0, 2)}:${str.slice(2, 4)}:${str.slice(4, 6)}`;
        };
        return <span>{text !== null && text !== undefined ? formatTime(text) : '-'}</span>;
      },
    },
    {
      title: '第一次上板时间',
      align: 'center',
      dataIndex: 'firstFbTime',
      key: 'firstFbTime',
      render: (text: number) => {
        const formatTime = (time: number) => {
          const str = time.toString().padStart(6, '0');
          return `${str.slice(0, 2)}:${str.slice(2, 4)}:${str.slice(4, 6)}`;
        };
        return <span>{text !== null && text !== undefined ? formatTime(text) : '-'}</span>;
      },
    },
    {
      title: '最近上板次数',
      align: 'center',
      dataIndex: 'lbTotal',
      key: 'lbTotal',
    },
    {
      title: '涨停原因',
      align: 'center',
      dataIndex: 'remark',
      key: 'remark',
    },
  ];

  useEffect(() => {
    getNewJyr()
      .then(date => {
        setCurJyr(date);
        getZtbData({jyr: date})
          .then(data => setLbData(data))
          .catch(error => console.error('Error fetching index data:', error));
        getTodayBk({jyr: date,pcode: null})
          .then(data => {
            const tableDataWithChildren = data.map(item => ({ ...item, children: [],isParent: true }));
            setTableData(tableDataWithChildren);
            getStockData({ jyr: date, bkcode: data[0].code,isParent: true})
              .then(data2 => setTable2Data(data2))
              .catch(error2 => console.error('Error fetching stock data:', error2)); 
              })

          .catch(error => console.error('Error fetching block data:', error)); 
      })
      .catch(error => console.error('Error fetching trading date:', error));
    getDpInfo().then(data => {
          setDpInfo(data); 
          getAllDpInfo().then(dpInfos => {
            if (!dpInfos) return;
            if(dpInfos[0].jyr != data.jyr){
              dpInfos.unshift(data);
            }
            setLineData(dpInfos.map(item => ({ date: item.jyr.toString(), value: item.qd })));
            setColumnData(dpInfos.map(item => ({ date: item.jyr.toString(), value: Number(item.fValue)/10000000 })));
          });
        });  
  }, []);


  const handleExpand = (expanded, record) => {
    if (expanded) {
      getTodayBk({jyr: curJyr, pcode: record.code})
        .then(data => {
          const newTableData = tableData.map(item => {
            if (item.code === record.code) {
              return { ...item, children: data ,isParent: true};
            }
            return item;
          });

          setTableData(newTableData);
          setExpandedRowKeys([...expandedRowKeys, record.code]);
        })
        .catch(error => console.error('Error fetching child data:', error));
    } else {
      setExpandedRowKeys(expandedRowKeys.filter(key => key !== record.code));
    }
  };

  const handleCodeClick = (code: string,isParent:any) => {
    getStockData({ jyr: curJyr, bkcode: code,isParent: isParent})
      .then(data => setTable2Data(data))
      .catch(error => console.error('Error fetching stock data:', error));
  };
  const handleBkMonitor = (code: string,isParent:any) => {
    insertBkMonitor({ jyr: curJyr, bkcode: code,isParent: isParent })
    .then(() => {
      message.success('成功添加');
    })
  }
  const handleStockMonitor = (code: string,bkCode:string) => {
    insertStockMonitor({ jyr: curJyr, code: code,bkcode: bkCode })
    .then(() => {
      message.success('成功添加');
    })
  }

  const handleStockClick = (code: any) => {
    setSelectedStockData(code);
    setIsModalVisible(true);
  };

  const handleModalClose = () => {
    setIsModalVisible(false);
    setSelectedStockData(null);
  };
  return (
    <div className="pl-4">
    <Row gutter={[16, 16]}>
      <Col span={8}>
        <Card title="市场情绪">
        <div style={{ height: '300px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div style={{ display: 'flex', width: '100%' }}>
              <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'space-around', alignItems: 'center' }}>
                <div style={{ width: '100%', display: 'flex', alignItems: 'center' }}>
                  <div>涨停家数</div>
                  <Progress percent={(dpInfo.ztNum / 100) * 100} strokeColor="red" showInfo={false} style={{ flex: 1, marginLeft: '10px' }} />
                  <div style={{ marginLeft: '10px' }}>{dpInfo.ztNum}</div>
                </div>
                <div style={{ width: '100%', display: 'flex', alignItems: 'center' }}>
                  <div>跌停家数</div>
                  <Progress percent={(dpInfo.dtNum / 100) * 100} strokeColor="green" showInfo={false} style={{ flex: 1, marginLeft: '10px' }} />
                  <div style={{ marginLeft: '10px' }}>{dpInfo.dtNum}</div>
                </div>
                <div style={{ width: '100%', display: 'flex', alignItems: 'center' }}>
                  <div>上涨家数</div>
                  <Progress percent={(dpInfo.szNum / 6000) * 100} strokeColor="red" showInfo={false} style={{ flex: 1, marginLeft: '10px' }} />
                  <div style={{ marginLeft: '10px' }}>{dpInfo.szNum}</div>
                </div>
                <div style={{ width: '100%', display: 'flex', alignItems: 'center' }}>
                  <div>下跌家数</div>
                  <Progress percent={(dpInfo.xdNum / 6000) * 100} strokeColor="green" showInfo={false} style={{ flex: 1, marginLeft: '10px' }} />
                  <div style={{ marginLeft: '10px' }}>{dpInfo.xdNum}</div>
                </div>
              </div>
              <div style={{ flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                <Progress type="circle" percent={dpInfo.qd} strokeColor={getCircleColor(dpInfo.qd)} />
              </div>
            </div>
          </div>
        </Card>
      </Col>
      <Col span={16}>
        <Card title="市场强度走势">
          <div style={{ height: '300px' }}>
            <ReactECharts option={getCombinedOption()} style={{ height: '100%' }} />
          </div>
        </Card>
      </Col>
    </Row>
    <Row className="row-spacing">
      <Col span={10} className='table-spacing'>
      <Table
            columns={columns}
            dataSource={tableData}
            pagination={false}
            rowKey="code"
            expandable={{
              expandedRowKeys,
              onExpand: handleExpand,
              rowExpandable: record => !record.children,
              expandIcon: ({ expanded, onExpand, record }) =>
                record.children ?  expanded ? (
                  <MinusCircleTwoTone
                    onClick={e => onExpand(record, e)}
                    style={{ fontSize: '10px',marginRight: '8px', display: 'flex', alignItems: 'center', justifyContent: 'flex-start'  }}
                  />
                ) : (
                  <PlusCircleTwoTone
                    onClick={e => onExpand(record, e)}
                    style={{ fontSize: '10px',marginRight: '8px', display: 'flex', alignItems: 'center', justifyContent: 'flex-start'  }}
                  />
                ):null,
              fixed: true,
              expandIconColumnIndex: 0,
            }}
            className="custom-table-cell table1" 
          />
        </Col>
        <Col span={14}>
          <Table
            columns={columns2}
            dataSource={table2Data}
            pagination={{ pageSize: 20 }}
            rowKey="stockCode"
            className="custom-table-cell" 
          />
        </Col>
      </Row>
      <Row className="row-spacing">
      <Col span={24}>
          <Table
            columns={columns3}
            dataSource={lbData}
            pagination={false}
            className="custom-table-cell" 
            rowKey="stock"
          />
        </Col>
      </Row>
      
      
      <Modal
        title="股票K线走势图"
        visible={isModalVisible}
        onCancel={handleModalClose}
        footer={null}
        width={800}
      >
        {selectedStockData && <KLines code={selectedStockData} />}
      </Modal>
    </div>
  );
};

export default MyComponent;